package com.kaifamiao.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;

/**
 * 使用 PreparedStatement 执行 DML 语句
 */
public class JdbcTest08 {

    public static void main(String[] args) throws SQLException {
        DbHelper dh = new DbHelper();
        dh.load();
        Connection c = dh.connect();

        // 提供带有参数占位符的SQL语句
        String sql = "INSERT INTO t_staff ( name , gender , hiredate , id ) VALUES ( ? , ? , ? , ? )" ;
        // 使用指定的SQL语句创建 PreparedStatement 对象
        PreparedStatement ps = c.prepareStatement( sql );
        System.out.println( ps );

        // 设置参数占位符的值
        ps.setString( 1 , "曾子豪" );
        ps.setString( 2 , "male" );
        LocalDate d = LocalDate.of( 2021 , 12 , 31 );
        java.sql.Date date = java.sql.Date.valueOf( d );
        ps.setDate( 3 , date );
        ps.setInt( 4 , 1001 );

        System.out.println( ps );

        c.setAutoCommit( false );

        try{
            int count = ps.executeUpdate();
            System.out.println( count );
            c.commit();
        } catch ( SQLException e ) {
            c.rollback();
        }

        c.setAutoCommit( true );

        dh.release( ps );
        dh.release( c );

    }

}
